#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2025/3/26 10:03:49
# @File           : crud.py
# @IDE            : PyCharm
# @desc           : 辅料需求

from fastapi import APIRouter, Depends, Path
from utils.response import SuccessResponse
from . import schemas, crud, params, models
from core.dependencies import IdList
from core.crud import construct_filter
from ..taskpool.models import DCTask
from ...base.auth.validate import Auth, AllUserAuth
from sqlalchemy.orm import joinedload


app = APIRouter()


###################################################
#     辅料需求                                     #
###################################################
@app.get("/task/need", summary="获取生产任务辅料需求")
async def get_need_list(
        p: params.TaskNeedParams = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    v_where = None
    if p.task:
        v_where = construct_filter(DCTask, **p.task)
    del p.task
    datas, count = await crud.TaskNeedDal(auth.db).get_datas(
        **p.dict(),
        v_schema=schemas.TaskNeedOut,
        v_return_count=True,
        v_join=[["task"]],
        v_options=[joinedload(models.DCTaskNeed.task)],
        v_where=v_where
    )
    return SuccessResponse(datas, count=count)


@app.get("/task/{ticket_id}/need", summary="获取生产任务辅料需求")
async def get_need(
        ticket_id: str,
        auth: Auth = Depends(AllUserAuth())
):
    datas, count = await crud.TaskNeedDal(auth.db).get_datas(
        v_join=[["task"]],
        v_where=[DCTask.ticket_id == ticket_id],
        v_schema=schemas.TaskNeedSimpleOut,
        v_return_count=True
    )
    return SuccessResponse(datas, count=count)


@app.post("/task/need", summary="创建生产任务辅料需求")
async def post_need(
        data: schemas.TaskNeed,
        auth: Auth = Depends(AllUserAuth())
):
    data.create_user = auth.user.user_str
    return SuccessResponse(await crud.TaskNeedDal(auth.db).create_data(data=data))


@app.put("/task/need/{data_id}", summary="更新生产任务辅料需求")
async def put_need(data_id: int, data: schemas.TaskNeed, auth: Auth = Depends(AllUserAuth())):
    data.update_user = auth.user.user_str
    return SuccessResponse(await crud.TaskNeedDal(auth.db).put_data(data_id, data=data))


@app.delete("/task/need", summary="批量删除辅料需求", description="硬删除")
async def delete_need(ids: IdList = Depends(), auth: Auth = Depends(AllUserAuth())):
    await crud.TaskNeedDal(auth.db).delete_datas(ids=ids.ids, v_soft=True)
    return SuccessResponse("删除成功")
